package com.tanhua.autoconfig.template;

import com.tanhua.autoconfig.properties.SmsProperties;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.IOException;

/**
 * 互亿无线短信服务组件
 * @author Xiao
 * @date 2021/10/21
 */
public class SmsTemplate {
    private SmsProperties smsProperties;
    public SmsTemplate(SmsProperties smsProperties) {
        this.smsProperties = smsProperties;
    }

    public void sendSms(String mobile, String code) {
        String Url = smsProperties.getUrl();
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(Url);

        client.getParams().setContentCharset("UTF-8");
        method.setRequestHeader("ContentType",
                "application/x-www-form-urlencoded;charset=UTF-8");

//        int mobile_code = (int) ((Math.random() * 9 + 1) * 100000);

        String content = new String("您的验证码是：" + code + "。请不要把验证码泄露给其他人。");

        NameValuePair[] data = {//提交短信
                //查看用户名 登录用户中心->验证码通知短信>产品总览->API接口信息->APIID
                new NameValuePair("account", smsProperties.getAccount()),
                //查看密码 登录用户中心->验证码通知短信>产品总览->API接口信息->APIKEY
                new NameValuePair("password", smsProperties.getPassword()),
                //new NameValuePair("password", util.StringUtil.MD5Encode("密码")),
                new NameValuePair("mobile", mobile),
                new NameValuePair("content", content),
        };
        method.setRequestBody(data);
        try {
            client.executeMethod(method);
            String submitResult = method.getResponseBodyAsString();
            System.out.println(submitResult);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
